import { $ } from './library/jquery-module.js';
import { cookie } from './library/cookie.js';


function addItem(id, price, num) {
    let shop = cookie.get('shop');
    let product = {
        id,
        price,
        num
    };

    if (shop) {
        shop = JSON.parse(shop);

        // 判断当前的商品id在cookie数据中是否存在
        if (shop.some(el => el.id === id)) {
            shop.forEach(elm => {
                elm.id === id ? elm.num = num : null;
            });
        } else {
            shop.push(product);
        }


    } else { // 没有存cookie的情况
        shop = []; // 初始化成数组
        shop.push(product);
    }

    cookie.set('shop', JSON.stringify(shop), 1);
}

// 设置cookie
$('.tab2 .card').on({
    'click': function() {
        let id = $(this).prev().prev().attr('data-id');
        let price = $(this).prev().prev().text().slice(1);
        let num = $(this).prev().children('.num-vaule').text();
        // console.log(id, price, num);
        addItem(id, price, num);
        location.href = "./detail.html";
    }
}, '.btn-warning');